package com.fsserver;

import com.fsserver.common.utils.MDCTraceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 支付服务启动类
 *
 * @author fsserver
 * @date 2023-03-13
 */
@SpringBootApplication
public class PayServiceApplication {
    private static final Logger log = LoggerFactory.getLogger(PayServiceApplication.class);

    public static void main(String[] args) {
        try {
            // 生成启动追踪ID
            String startupTraceId = MDCTraceUtils.generateTraceId();
            MDCTraceUtils.setTraceId(startupTraceId);
            
            // 记录启动开始时间
            long startTime = System.currentTimeMillis();
            
            // 启动Spring应用
            log.info("=== 支付服务开始启动 [traceId: {}] ===", startupTraceId);
            SpringApplication app = new SpringApplication(PayServiceApplication.class);
            ConfigurableApplicationContext context = app.run(args);
            
            // 获取环境信息
            Environment env = context.getEnvironment();
            String appName = env.getProperty("spring.application.name");
            String port = env.getProperty("server.port");
            String contextPath = env.getProperty("server.servlet.context-path", "");
            String hostAddress = "localhost";
            
            try {
                hostAddress = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                log.warn("无法确定主机地址", e);
            }
            
            // 计算启动耗时
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            
            // 输出启动成功信息
            log.info("=== 支付服务启动成功 [traceId: {}] ===", startupTraceId);
            log.info("应用名称: {}", appName);
            log.info("运行环境: {}", env.getActiveProfiles()[0]);
            log.info("本地访问: http://localhost:{}{}", port, contextPath);
            log.info("外部访问: http://{}:{}{}", hostAddress, port, contextPath);
            log.info("Swagger文档: http://{}:{}{}/api/doc.html", hostAddress, port, contextPath);
            log.info("启动耗时: {}ms", duration);
            
            // 清除MDC上下文
            MDCTraceUtils.clear();
        } catch (Exception e) {
            log.error("支付服务启动失败", e);
            // 确保MDC上下文被清除
            MDCTraceUtils.clear();
            // 退出应用
            System.exit(1);
        }
    }
} 